package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动实例化与当前ReflectDemo8在同一个包下所有被@AutoRunClass标注的类
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(ReflectDemo8.class.getResource(".").toURI());
        File[] files = dir.listFiles(f->f.getName().contains(".class"));
        for (File file : files){
            String fileName = file.getName().substring(0,file.getName().lastIndexOf("."));
            Class cls = Class.forName(ReflectDemo8.class.getPackage().getName()+"."+fileName);
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                System.out.println("实例化："+fileName);
                Object o = cls.newInstance();
                System.out.println(o);
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods){
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        //通过方法对象获取在该方法上使用的注解@AutoRunMethod
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        //通过注解对象获取传给value的值
                        int num = arm.value();
                        System.out.println("自动调用方法："+method.getName());
                        for (int i = 0;i<num;i++){
                            method.invoke(o);
                        }
                    }
                }
            }
        }
    }
}
